package net.guoyixian.common.datasource;

import java.lang.reflect.Method;

import net.guoyixian.common.datasource.DataSource.SourceType;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

public class DataSourceAspect {
	private static Logger log = Logger.getLogger(DataSourceAspect.class);

	public void before(JoinPoint point) {
		try {
			// 1、获得方法签名Signature,并将Signature转换成MethodSignature
			Signature signature = point.getSignature();
			MethodSignature methodSignature = (MethodSignature) signature;// 转换为MethodSignature
			//2、获取方法
			Method m = methodSignature.getMethod();
			//3、判断方法是否有DataSource.class的注解
			if (m != null && m.isAnnotationPresent(DataSource.class)) {
				// 4、数据源holder赋值为注解的值
				DataSource data = m.getAnnotation(DataSource.class);
				DynamicDataSourceHolder.putDataSource(data.value());
				log.debug("=========已指定mysql数据源，为：" + data.value() + "===========");
			}else{
				//5、其他情况，数据库切换为MASTER
				DynamicDataSourceHolder.putDataSource(SourceType.MASTER);
				log.debug("=========未指定mysql数据源，默认为：MASTER===========");
			}
		} catch (Exception e) {
			// 打印出堆栈信息
			log.error("==========数据源切换出现错误============", e);
		}
	}
}